package com.nowcoder.community.controller;

import com.nowcoder.community.service.AlphaService;
import com.nowcoder.community.util.CommunityUtil;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

@Controller
@RequestMapping("alpha")
public class AlphaController {

    @Autowired
    private AlphaService alphaService;

    @RequestMapping("hello")
    public String saveHello(){
        return "Hellp Spring Boot";
    }

    @RequestMapping("/data")
    public String getData(){
        return alphaService.find();
    }

    @RequestMapping("/http")
    public  void  http(HttpServletRequest request, HttpServletResponse response){
        //获取请求数据
        System.out.println(request.getMethod());
        System.out.println(request.getServletPath());

        Enumeration<String> enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements()){
            String name = enumeration.nextElement();
            String value = request.getHeader(name);
            System.out.println(name+":" +value);
        }
        System.out.println(request.getParameter("code"));

        //返回响应数据
        response.setContentType("text/html;charset=utf-8");
        try(//获取输出流对象通过底层封装的输出流输出
            PrintWriter writer = response.getWriter();
            )
        {
            writer.write("<h1>牛客网</h1> ");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    //Get请求
    //  /students?current = 1 && limit =20
    @RequestMapping(path = "/students",method = RequestMethod.GET)
    @ResponseBody
    public String getStudent(@RequestParam(name = "current",required = false,defaultValue = "1") int current,
                             @RequestParam(name = "limit",required = false,defaultValue = "10") int limit){
        System.out.println(current);
        System.out.println(limit);
        return "some student";

    }

    // student/123
    @RequestMapping(path = "/student/{id}",method = RequestMethod.GET)
    @ResponseBody
    public String getStudent(@PathVariable("id") int id){
        System.out.println(id);
        return "a student";

    }

    //Post请求
    @RequestMapping(path ="/student",method = RequestMethod.POST)
    @ResponseBody
    public String saveStudent(String name,int age){   //接受表单数据：参数与表单项名字一致，自动传入
        System.out.println(name);
        System.out.println(age);
        return "success" ;
    }

    //响应HTML数据
    @RequestMapping(path = "/teacher", method = RequestMethod.GET)
    public ModelAndView getTeacher(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("name","小米");
        modelAndView.addObject("age",18);
        //设置模版路径和名字
        modelAndView.setViewName("/demo/view");
        return modelAndView;
    }

    //更简洁
    @RequestMapping(path = "/school", method = RequestMethod.GET)
    public String getSchool(Model model){
       model.addAttribute("name","小华");
        model.addAttribute("age","88");
       //返回的是String类型，默认返回的是view的路径
        return "/demo/view";
    }

    //响应json数据(异步请求)
    //Java对象-->JSON字符串--->JS对象
    @RequestMapping(path ="/emp",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getEmp(){
        HashMap<String,Object> emp = new HashMap<>();
        emp.put("name","张珊");
        emp.put("age",23);
        emp.put("salary",8000);
        //自动将对象装换位JSON字符串
        return emp;
    }

    @RequestMapping(path ="/emps",method = RequestMethod.GET)
    @ResponseBody
    public List<Map<String,Object>> getEmps(){
        List<Map<String,Object>> list = new ArrayList<>();

        HashMap<String,Object> emp = new HashMap<>();
        emp.put("name","张珊");
        emp.put("age",23);
        emp.put("salary",8000);

        HashMap<String,Object> emp1 = new HashMap<>();
        emp1.put("name","张8");
        emp1.put("age",25);
        emp1.put("salary",7000);

        HashMap<String,Object> emp2 = new HashMap<>();
        emp2.put("name","张9");
        emp2.put("age",24);
        emp2.put("salary",5000);

        list.add(emp);
        list.add(emp1);
        list.add(emp2);
        //自动将对象装换位JSON字符串
        return list;
    }

    //Cookie示例
    //服务器下发cookie
    @RequestMapping(path = "/cookie/set",method = RequestMethod.GET)
    @ResponseBody
    public String setCookie(HttpServletResponse response){
        //创建cookie
        Cookie cookie = new Cookie("code", CommunityUtil.generateUUID());
        //设置cookie生效范围
        cookie.setPath("/community/alpha");
        //设置cookie生存时间
        cookie.setMaxAge(60*10);
        //发送cookie，添加到response头部，自动发送
        response.addCookie(cookie);

        return "set cookie";
    }

    //浏览器携带cookie
    @RequestMapping(path ="cookie/get",method = RequestMethod.GET)
    @ResponseBody  //将字符串映射为json
    public String getCookie(@CookieValue("code") String code){  //@CookieValue("code") 获取cookie中指定键的值
        System.out.println(code);
        return "get cookie";
    }

    //Session示例
    //创建session,底层自动创建cookie并保存sessionId返回
    @RequestMapping(path ="session/set",method = RequestMethod.GET)
    @ResponseBody  //将字符串映射为json
    public String setSession(HttpSession session){  //SpringMVC 自动创建session，声明时自动注入
        //向session中添加内容
        session.setAttribute("id",1);
        session.setAttribute("name","Test");
        return "set session";
    }


    @RequestMapping(path ="session/get",method = RequestMethod.GET)
    @ResponseBody  //将字符串映射为json
    public String getSession(HttpSession session){  //SpringMVC 自动创建session，声明时自动注入
        //从session中获取信息
        System.out.println( session.getAttribute("id"));
        System.out.println( session.getAttribute("name"));
        return "get session";
    }

    //ajax示例
    @PostMapping("/ajax")
    @ResponseBody
    public String testAjax(String name,int age){
        System.out.println(name);
        System.out.println(age);
        return CommunityUtil.getJSONString(0,"操作成功");
    }
}
